// index.js
// 获取应用实例
const app = getApp()
const util = require("../../utils/util")
const api = require("../../utils/api")
const bluetoothUtils = require("../../utils/bluetoothUtils")
const network = require("../../utils/network")
Page({
    data: {
        videoUrl: 'https://download.app.smartbed.ink/inland/hotel/qs_hotel/product.mp4',
        dialogShow: false,
        dialogShow2: false,
        hasConnect: false,
        msg: {
            content: '当前未连接智能床，是否立即连接',
            title: '',
            btntext: '立即连接',
            tips: 1
        },
        func: 0,
        bluetoothFlag: false, //手机蓝牙未开启标志位
        bluetoothFlag2: false, //微信蓝牙未授权标志位
        hasconnect: false,
    },
    toOneButton: function () {
        app.globalData.bluetooth_connected = true
        if (app.globalData.nopermission == true) {
            util.myShowLoading('请先授权')
            setTimeout(() => {
                this.setData({
                    dialogShow: true
                })
                util.myHideLoading()
            }, 1000)
        } else {
            if (app.globalData.deviceId == null) {
                this.setData({
                    dialogShow2: true,
                    'msg.content': '当前未连接智能床，是否立即连接',
                    'msg.title': '',
                    'msg.btntext': '立即连接',
                    'msg.tips': 1,
                    func: 0
                })
            } else {
                if (app.globalData.bluetooth_connected == true) {
                    wx.navigateTo({
                        url: '/pages/index/oneButtonSleep/onbuttonsleep',
                    })
                } else {
                    this.permissionCheck(0)
                }
            }
        }
    },
    toRemote: function () {
        if (app.globalData.nopermission == true) {
            util.myShowLoading('请先授权')
            setTimeout(() => {
                this.setData({
                    dialogShow: true
                })
                util.myHideLoading()
            }, 1000)

        } else {
            if (app.globalData.deviceId == null) {
                this.setData({
                    dialogShow2: true,
                    'msg.content': '当前未连接智能床，是否立即连接',
                    'msg.title': '',
                    'msg.btntext': '立即连接',
                    'msg.tips': 1,
                    func: 1
                })
            } else {
                if (app.globalData.bluetooth_connected == true) {
                    wx.navigateTo({
                        url: '/pages/index/remote/remote',
                    })
                } else {
                    this.permissionCheck(1)
                }
            }
        }
    },
    toRelax: function () {
        if (app.globalData.nopermission == true) {
            util.myShowLoading('请先授权')
            setTimeout(() => {
                this.setData({
                    dialogShow: true
                })
                util.myHideLoading()
            }, 1000)
        } else {
            if (app.globalData.deviceId == null) {
                this.setData({
                    dialogShow2: true,
                    'msg.content': '当前未连接智能床，是否立即连接',
                    'msg.title': '',
                    'msg.btntext': '立即连接',
                    'msg.tips': 1,
                    func: 2
                })
            } else {
                if (app.globalData.bluetooth_connected == true) {
                    wx.navigateTo({
                        url: '/pages/index/smartRelax/smartrelax',
                    })
                } else {
                    this.permissionCheck(2)
                }
            }
        }
    },
    toRealTime: function () {
        if (app.globalData.nopermission == true) {
            util.myShowLoading('请先授权')
            setTimeout(() => {
                this.setData({
                    dialogShow: true
                })
                util.myHideLoading()
            }, 1000)
        } else {
            if (app.globalData.deviceId == null) {
                this.setData({
                    dialogShow2: true,
                    'msg.content': '当前未连接智能床，是否立即连接',
                    'msg.title': '',
                    'msg.btntext': '立即连接',
                    'msg.tips': 1,
                    func: 3
                })
            } else {
                if (app.globalData.bluetooth_connected == true) {
                    wx.navigateTo({
                        url: '/pages/index/realTimeData/realtime',
                    })
                } else {
                    this.permissionCheck(3)
                }

            }
        }
    },
    toAlarm: function () {
        if (app.globalData.nopermission == true) {
            util.myShowLoading('请先授权')
            setTimeout(() => {
                this.setData({
                    dialogShow: true
                })
                util.myHideLoading()
            }, 1000)
        } else {
            if (app.globalData.deviceId == null) {
                this.setData({
                    dialogShow2: true,
                    'msg.content': '当前未连接智能床，是否立即连接',
                    'msg.title': '',
                    'msg.btntext': '立即连接',
                    'msg.tips': 1,
                    func: 3
                })
            } else {
                if (app.globalData.bluetooth_connected == true) {
                    if (app.globalData.hasalarm == true) {
                        wx.navigateTo({
                            url: '/pages/index/alarm/alarm',
                        })
                    } else {
                        wx.navigateTo({
                            url: '/pages/index/alarm/setAlarm/setalarm',
                        })
                    }
                }
                // else {
                //     this.permissionCheck(3)
                // }

            }
        }
    },
    //协议弹窗
    dialogHandle: function (e) {
        const _this = this
        console.log('params', e.detail.params)
        this.setData({
            dialogShow: e.detail.params
        })
        if (e.detail.text == 'confirm') {
            app.globalData.nopermission = false
            let data = {
                open_id: app.globalData.openid
            }
            console.log('data,11111', data)
            api.login(data).then(res => {
                if (res.data.code == 200) {
                    app.globalData.token = res.data.data.token
                    app.globalData.userId = res.data.data.user_id
                } else {
                    console.log('error', res.data.msg)
                }
            })
        } else {
            wx.exitMiniProgram({
                success: (res) => {}
            })
        }
    },
    //连接床弹窗
    dialogHandle2: async function (e) {
        this.setData({
            dialogShow2: e.detail.params
        })
        if (e.detail.text == 'confirm') {
            if (app.globalData.nopermission == false) {
                //先检查手机蓝牙是否打开
                if (this.data.msg.btntext == '订阅') {
                    console.log('needsubscribe2222===>', app.globalData.needsubscribe)
                    // app.globalData.needsubscribe = false
                    // app.globalData.subscribeFlag = false
                    await util.subscribe()
                    // return
                } else {
                    //是否连接弹窗
                    this.permissionCheck(this.data.func)
                }
            } else {
                // util.myShowLoading('请先授权')
                util.myShowToast('请先授权')
                setTimeout(() => {
                    this.setData({
                        dialogShow: true
                    })
                    util.myHideLoading()
                }, 1000)

            }
        } else if (e.detail.text == 'cancel') {
            if (this.data.msg.btntext == '订阅') {
                app.globalData.needsubscribe = false
                app.globalData.subscribeFlag = false
            }
        }
    },
    //蓝牙重连逻辑处理
    reconnectHandle: async function () {
        bluetoothUtils.myShowLoading('智能床连接中')
        let code = await bluetoothUtils.oneTouchConnectBluetooth(app.globalData.deviceId)
        await bluetoothUtils.errorHandle(code)
        if (code != 100) {
            return
        }
        if (app.globalData.deviceId2 != null) {
            let code2 = await bluetoothUtils.oneTouchConnectBluetooth(app.globalData.deviceId2)
            console.log('1号蓝牙连接状态====>', app.globalData.bluetooth_connected)
            if (app.globalData.bluetooth_connected2 == false) {
                console.log('1号蓝牙信息====>', app.globalData.bluetoothInfo)
                if (app.globalData.bluetoothInfo != null) {
                    console.log('app.globalData.bluetoothInfo', app.globalData.bluetoothInfo, app.globalData.bluetoothInfo.deviceID)
                    bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo.deviceID)
                    app.globalData.bluetooth_connected = false
                }
            }
            await bluetoothUtils.wait(0.5)
            await bluetoothUtils.errorHandle(code2)
        }

    },
    //蓝牙权限检查
    permissionCheck: function (index) {
        let _this = this
        let pathArr = ['/oneButtonSleep/onbuttonsleep', '/remote/remote', '/smartRelax/smartrelax', '/realTimeData/realtime']
        wx.getSetting({
            withSubscriptions: true,
            success(res) {
                console.log('blue', res)
                // if (res.authSetting["scope.bluetooth"] == true && res.authSetting["scope.userLocation"] == true) {  蓝牙权限及位置权限是否打开(位置暂时不需要)
                if (res.authSetting["scope.bluetooth"] == true) {
                    wx.openBluetoothAdapter({
                        success: async function (res) {
                            if (app.globalData.scan_device_id != null) { //有水牌码
                                api.bedSide({
                                    qrcode: app.globalData.scan_device_id
                                }, app.globalData.token).then(async function (res) {
                                    console.log('res', res.data.data)
                                    app.globalData.scan_device_id = null
                                    if (res.data.data) {
                                        if (app.globalData.deviceId == res.data.data.left_device_id || app.globalData.deviceId == res.data.data.right_device_id) {
                                            _this.reconnectHandle()
                                            if (app.globalData.bluetooth_connected == true) {
                                                this.setData({
                                                    dialogShow2: true,
                                                    'msg.content': '当前未订阅睡眠报告信息推送，是否订阅？',
                                                    'msg.title': '',
                                                    'msg.btntext': '订阅',
                                                    'msg.tips': 1
                                                })
                                            }
                                        } else {
                                            wx.navigateTo({
                                                url: '/pages/connect/bedside/bedside?obj=' + JSON.stringify(res.data.data),
                                            })
                                        }

                                    }
                                })
                            } else { //无水牌码
                                console.log('有设备号', app.globalData.deviceId)
                                if (app.globalData.deviceId != null) { //有设备号
                                    if (app.globalData.needConnect == true) { //需要重连
                                        _this.reconnectHandle()
                                    } else { //无需重连
                                        bluetoothUtils.myHideLoading()
                                        wx.navigateTo({
                                            url: '/pages/index' + pathArr[index],
                                        })
                                    }
                                } else { //无设备号
                                    // util.myHideLoading()
                                    if (index != 100) {
                                        _this.scan(index)
                                    }

                                }
                            }
                        },
                        fail: function (res) { //手机上的蓝牙没有打开
                            // util.myHideLoading()
                            _this.setData({
                                bluetoothFlag: true
                            })
                        }
                    })
                } else if (res.authSetting["scope.bluetooth"] == undefined) {
                    // util.myHideLoading()
                    wx.authorize({
                        scope: "scope.bluetooth",
                        success() {
                            // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                            _this.permissionCheck()
                        }
                    })
                } else if (res.authSetting["scope.bluetooth"] == false) {
                    // util.myHideLoading()
                    _this.setData({
                        bluetoothFlag2: true
                    })
                }
            }
        })
    },
    //扫码
    scan: function (index) {
        let _this = this
        let pathArr = ['/oneButtonSleep/onbuttonsleep', '/remote/remote', '/smartRelax/smartrelax', '/realTimeData/realtime']
        wx.scanCode({
            onlyFromCamera: true,
            success: async function (res) {
                console.log('扫码携带的参数', res)
                let bed_qrcode = ''
                let params = {}
                if (res.result) {
                    if (res.result.length > 16) {
                        bed_qrcode = res.result.split('#')[0].substring(res.result.split('#')[0].length - 16, res.result.split('#')[0].length)
                    } else {
                        bed_qrcode = res.result
                    }
                } else if (res.q) {
                    bed_qrcode = res.q.substring(res.q.length - 16, res.q.length)
                    console.log('code', bed_qrcode)
                } else {}
                params.qrcode = bed_qrcode
                api.bedSide(params).then(res => {
                    //获取床边信息完成
                    if (res.data.code == 200) {
                        if (res.data.data.left_device_id != null && res.data.data.right_device_id) {
                            console.log('device_id=====>', app.globalData.failDevice, res.data.data.left_device_id, res.data.data.right_device_id)
                            if (app.globalData.failDevice == res.data.data.left_device_id || app.globalData.failDevice == res.data.data.right_device_id) {
                                wx.navigateTo({
                                    url: '/pages/connect/bedside/bedside?obj=' + JSON.stringify(res.data.data) + '&reconnect=true',
                                })
                            } else {
                                wx.navigateTo({
                                    url: '/pages/connect/bedside/bedside?obj=' + JSON.stringify(res.data.data) + "&path=" + pathArr[index],
                                })
                            }

                        } else {
                            console.log(res)
                            // util.myShowToast('请扫描正确二维码')
                            _this.setData({
                                dialogShow2: true,
                                'msg.content': '连接失败，请重新扫码连接',
                                'msg.btntext': '重新连接',
                                'msg.title': '',
                                'msg.tips': 3
                            })
                            return
                        }
                    } else {
                        console.log(res)
                        util.myShowToast('请扫描正确二维码')
                        return
                    }
                })
            },
            fail: function (res) {
                // util.myShowToast("用户操作已取消")
            }
        })
    },
    //弹窗取消
    cancel: function () {
        this.setData({
            bluetoothFlag: false,
            bluetoothFlag2: false,
            // userLocationFlag: false
        })
    },
    updata: function () {
        const _this = this
        if (app.globalData.nopermission == true) {
            _this.setData({
                dialogShow: true
            })
        }
    },
    updata2: async function () {
        const _this = this
        if (app.globalData.needsubscribe == true) {
            await bluetoothUtils.wait(0.3)
            this.setData({
                dialogShow2: true,
                'msg.content': '当前未订阅睡眠报告信息推送，是否订阅？',
                'msg.title': '',
                'msg.btntext': '订阅',
                'msg.tips': 1
            })
        }
    },
    initMyPage() {
        if (app.globalData.nopermission == true) {
            this.setData({
                dialogShow: true
            })
        } else {
            this.setData({
                dialogShow: false
            })
            if (app.globalData.scan_device_id != null) { //扫水牌进入
                this.permissionCheck()
            } else { //不扫水牌
                this.permissionCheck(100)
            }
        }
    },
    //
    onLoad(options) {
        // wx.onBLEConnectionStateChange(listener)
        app.watchProperty(this.updata, 'nopermission', true);
        console.log('nopermission', app.globalData.nopermission)
        console.log('options', JSON.stringify(options))
        let _this = this
        //水牌处理，获取设备号，全局存储
        if (JSON.stringify(options) != '{}') {
            if (options.q) {
                app.globalData.scan_device_id = options.q.substring(options.q.length - 16, options.q.length) //处理水牌
                console.log('options.q', options.q.substring(options.q.length - 16, options.q.length))
            }
        }
        util.login().then(() => {
            _this.initMyPage()
        })

    },
    onShow() {
        app.watchProperty(this.updata2, 'needsubscribe', null);
        console.log('needsubscribe', app.globalData.needsubscribe, app.globalData.subscribeFlag)
    }
})